# 业务: 三台电脑同一时刻共同调用打印机,完成打印业务.
# 3个进程,同一时刻共抢一个资源: 输出平台.
# from multiprocessing import Process
# import time
# import random
# def task1():
#     print('task1: 开始打印')
#     time.sleep(random.randint(1,3))
#     print('task1: 打印完成')
#
# def task2():
#     print('task2: 开始打印')
#     time.sleep(random.randint(1, 3))
#     print('task2: 打印完成')
#
# def task3():
#     print('task3: 开始打印')
#     time.sleep(random.randint(1, 3))
#     print('task3: 打印完成')
#
# if __name__ == '__main__':
#     p1 = Process(target=task1,)
#     p2 = Process(target=task2,)
#     p3 = Process(target=task3,)
#
#     p1.start()
#     p2.start()
#     p3.start()

# 多个进程共抢一个资源,你要是做到结果第一位,效率第二位.
# 你应该牺牲效率,保求结果.串行.

# 版本二:

# from multiprocessing import Process
# import time
# import random
# def task1():
#     print('task1: 开始打印')
#     time.sleep(random.randint(1,3))
#     print('task1: 打印完成')
#
# def task2():
#     print('task2: 开始打印')
#     time.sleep(random.randint(1, 3))
#     print('task2: 打印完成')
#
# def task3():
#     print('task3: 开始打印')
#     time.sleep(random.randint(1, 3))
#     print('task3: 打印完成')
#
# if __name__ == '__main__':
#     p1 = Process(target=task1,)
#     p2 = Process(target=task2,)
#     p3 = Process(target=task3,)
#
#     p2.start()
#     p2.join()
#     p1.start()
#     p1.join()
#     p3.start()
#     p3.join()

# 虽然说上面版本完成了串行结果,保证了顺序,但是没有实现公平.
# 顺序是人为写好的.我们要做到他公平去抢占打印机资源,谁先抢到,先执行谁.


# 三个人共住, 谁先起来谁先上厕所,你们抢的是厕所的那把锁,抢到锁锁上,你就上厕所.完事儿之后,打开锁.

# 版本三:


from multiprocessing import Process
from multiprocessing import Lock
import time
import random


def task1(lock):
    print('task1')  # 验证cpu遇到io切换了
    lock.acquire()
    print('task1: 开始打印')
    time.sleep(random.randint(1, 3))
    print('task1: 打印完成')
    lock.release()

def task2(lock):
    print('task2')  # 验证cpu遇到io切换了
    lock.acquire()
    print('task2: 开始打印')
    time.sleep(random.randint(1, 3))
    print('task2: 打印完成')
    lock.release()


def task3(lock):
    print('task3') # 验证cpu遇到io切换了
    lock.acquire()
    print('task3: 开始打印')
    time.sleep(random.randint(1, 3))
    print('task3: 打印完成')
    lock.release()


if __name__ == '__main__':

    lock = Lock()

    p1 = Process(target=task1, args=(lock,))
    p2 = Process(target=task2, args=(lock,))
    p3 = Process(target=task3, args=(lock,))

    p1.start()
    p2.start()
    p3.start()

# 上锁:
# 一定要是同一把锁: 只能按照这个规律:上锁一次,解锁一次.

# 互斥锁与join区别共同点? (面试题)

# 共同点: 都是完成了进程之间的串行.
# 区别: join认为控制的进程串行,互斥锁是随机的抢占资源.保证了公平性